package com.kizuki.thread;

public class TestSynchronized {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        Thread t1 = new Thread(buyTicket, "A");
        Thread t2 = new Thread(buyTicket, "B");
        Thread t3 = new Thread(buyTicket, "C");
        t1.start();
        t2.start();
        t3.start();
    }

}

class BuyTicket implements Runnable{
    private int num = 10;
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            synchronized (this) {
                buy();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

//    private synchronized void buy() {  // synchronized 方法同步，锁的是this
    private void buy() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "获得了第" + num + "张票");
            num --;
        } else {
            flag = false;
        }
//        Thread.sleep(1); //在同步代码块里面sleep 线程会变成阻塞状态但是不释放锁资源 直到就绪运行完后才释放
    }

}
